import gradio as gr
from agent.learning_agent import LearningAgent

# 创建学习代理实例
learning_agent = LearningAgent()

# Gradio界面函数
def on_grade_change(grade):
    """年级变化时更新科目选择"""
    subjects = learning_agent.knowledge_manager.get_subjects(grade)
    return gr.update(choices=subjects, value=subjects[0] if subjects else None)

def on_subject_change(grade, subject):
    """科目变化时更新知识点选择"""
    if not grade or not subject:
        return gr.update(choices=[], value=[])
    
    kp_options = learning_agent.knowledge_manager.get_knowledge_points(grade, subject)
    # 修复：直接使用kp_options中的(name, id)格式，而不是重新反转
    return gr.update(choices=kp_options, value=[])

def calculate_average_mastery(grade, subject):
    """计算当前科目下所有知识点的平均掌握程度"""
    if not grade or not subject:
        return 0
    
    # 获取当前科目的所有知识点
    subject_kps = learning_agent.knowledge_manager.get_knowledge_points(grade, subject)
    if not subject_kps:
        return 0
    
    total_mastery = 0
    count = 0
    
    # 计算每个知识点的掌握程度并求平均
    for kp_name, kp_id in subject_kps:
        if learning_agent.learning_memory:
            mastery_level = learning_agent.learning_memory.get_mastery_level(kp_id)
            total_mastery += mastery_level
            count += 1
    
    if count > 0:
        return total_mastery / count
    return 0

def start_learning(student_id, grade, subject, kp_ids):
        """开始学习"""
        if not all([student_id, grade, subject, kp_ids]):
            return "请填写完整信息", "", gr.update(choices=[], visible=True, interactive=True), gr.update(visible=False), gr.update(visible=False)
        
        # 初始化学生
        learning_agent.initialize_student(student_id)
        
        # 设置知识点
        learning_agent.set_knowledge_points(grade, subject, kp_ids)
        
        # 生成第一个题目
        question = learning_agent.generate_new_question()
        if not question:
            return "无法生成题目，请检查选择的知识点", "", gr.update(choices=[], visible=False), gr.update(visible=False), gr.update(visible=False)
        
        # 获取选项列表
        options_list = list(question["options"].values())
        
        # 计算并更新平均掌握程度
        average_mastery = calculate_average_mastery(grade, subject)
        learning_agent.current_grade = grade
        learning_agent.current_subject = subject
        
        return f"题目：{question['text']}", "", gr.update(choices=options_list, visible=True, interactive=True), gr.update(visible=True), gr.update(visible=False, interactive=False)

def submit_answer(user_answer):
        """提交答案"""
        if not user_answer or not learning_agent.current_question:
            # 使用gr.Warning显示弹出提示框
            gr.Warning("请选择一个答案")
            # 保留当前题目内容
            current_question_text = f"题目：{learning_agent.current_question['text']}" if learning_agent.current_question else ""
            # 获取选项列表
            options_list = list(learning_agent.current_question["options"].values()) if learning_agent.current_question else []
            # 获取当前平均掌握程度
            average_mastery = calculate_average_mastery(learning_agent.current_grade, learning_agent.current_subject)
            return "请选择一个答案", current_question_text, gr.update(choices=options_list, interactive=True), gr.update(visible=False, interactive=False), average_mastery, gr.update(visible=True, interactive=True)  # 不显示下一题按钮，保持提交行可见和可用
        
        # 修复：根据用户选择的选项文本找到对应的选项键
        user_answer_key = None
        for key, value in learning_agent.current_question["options"].items():
            if value == user_answer:
                user_answer_key = key
                break
        
        # 检查答案
        # 使用找到的选项键而不是直接使用用户答案
        is_correct, explanation = learning_agent.check_answer(user_answer_key)
        
        # 获取当前题目的正确答案文本
        correct_answer_key = learning_agent.current_question["correct_answer"]
        correct_answer_text = learning_agent.current_question["options"][correct_answer_key]
        
        # 获取选项列表并标记正确答案
        options_with_correct = []
        for key, value in learning_agent.current_question["options"].items():
            if key == correct_answer_key:
                options_with_correct.append(f"{value} [正确答案]")
            else:
                options_with_correct.append(value)
        
        # 获取学习进度
        progress = learning_agent.get_progress_summary()
        
        # 保留当前题目内容，不再将其清空
        current_question_text = f"题目：{learning_agent.current_question['text']}"
        
        # 计算并更新平均掌握程度
        average_mastery = calculate_average_mastery(learning_agent.current_grade, learning_agent.current_subject)
        
        # 提交答案后，隐藏提交答案按钮，显示并启用下一题按钮
        return (
            f"答案{'正确' if is_correct else '错误'}！{explanation}", 
            current_question_text,  # 保持题目内容显示
            gr.update(choices=options_with_correct, interactive=False, value=None),  # 禁用选项并清除选择
            gr.update(visible=True, interactive=True),  # 显示并启用下一题按钮
            average_mastery,  # 更新进度条显示平均分
            gr.update(visible=False)  # 隐藏提交答案按钮
        )


def next_question():
    """生成下一题"""
    # 生成新题目
    next_question = learning_agent.generate_new_question()
    if not next_question:
        return "无法生成下一题", "", gr.update(choices=[], visible=False), gr.update(visible=False), 0, gr.update(visible=True)  # 显示提交答案按钮
    
    # 获取选项列表
    options_list = list(next_question["options"].values())
    
    # 计算并更新平均掌握程度
    average_mastery = calculate_average_mastery(learning_agent.current_grade, learning_agent.current_subject)
    
    # 点击下一题后，显示提交答案按钮，隐藏下一题按钮
    return "", f"题目：{next_question['text']}", gr.update(choices=options_list, visible=True, interactive=True), gr.update(visible=False), average_mastery, gr.update(visible=True)  # 显示提交答案按钮



# 创建Gradio界面
def create_interface():
    with gr.Blocks(title="学生智能学习系统") as interface:
        gr.Markdown("# 学生智能学习系统")
        gr.Markdown("选择年级、科目和知识点，开始智能学习之旅！")
        
        with gr.Row():
            with gr.Column(scale=1):
                # 学生信息和选择区域
                student_id = gr.Textbox(label="学生ID", placeholder="请输入学生ID")
                
                grade = gr.Dropdown(
                    choices=learning_agent.knowledge_manager.get_grades(),
                    label="年级",
                    interactive=True
                )
                
                subject = gr.Dropdown(
                    choices=[],
                    label="科目",
                    interactive=True
                )
                
                knowledge_points = gr.CheckboxGroup(
                    choices=[],
                    label="知识点（可多选）",
                    interactive=True
                )
                
                start_button = gr.Button("开始学习")
                
                # 进度显示
                progress_display = gr.Slider(minimum=0, maximum=100, label="学习进度 (平均掌握程度)", interactive=False)
                
            with gr.Column(scale=2):
                # 题目和答题区域
                question_display = gr.Textbox(label="题目", interactive=False, lines=3)
                
                with gr.Row(visible=True) as options_row:
                    options_display = gr.Radio(choices=[], label="选项", interactive=True)
                    
                
                answer_status = gr.Textbox(label="答题结果", interactive=False, lines=3)
                
                with gr.Row(visible=False) as submit_row:
                    submit_button = gr.Button("提交答案")
                    next_button = gr.Button("下一题", interactive=False)

        # 设置事件监听
        grade.change(
            fn=on_grade_change,
            inputs=[grade],
            outputs=[subject]
        )
        
        subject.change(
            fn=on_subject_change,
            inputs=[grade, subject],
            outputs=[knowledge_points]
        )
        
        start_button.click(
            fn=start_learning,
            inputs=[student_id, grade, subject, knowledge_points],
            outputs=[question_display, answer_status, options_display, submit_row, next_button]
        )
        
        submit_button.click(
            fn=submit_answer,
            inputs=[options_display],  # 直接使用options_display作为输入
            outputs=[answer_status, question_display, options_display, next_button, progress_display, submit_button]
        )
        
        # 添加下一题按钮的点击事件绑定
        next_button.click(
            fn=next_question,
            inputs=[],
            outputs=[answer_status, question_display, options_display, next_button, progress_display, submit_button]
        )
        
    return interface